package com.wude.guild.fragment;

import android.annotation.SuppressLint;
import android.content.Intent;
import android.os.Bundle;
import android.os.CountDownTimer;
import android.os.Handler;
import android.os.Message;
import android.support.annotation.Nullable;
import android.text.TextUtils;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.EditText;
import android.widget.TextView;

import com.mc.developmentkit.utils.ToastUtil;
import com.umeng.analytics.MobclickAgent;
import com.wude.bean.UserInfo;
import com.wude.guild.R;
import com.wude.guild.RegisterActivity;
import com.wude.guild.WebActivity;
import com.wude.guild.servercore.app.CubeFragment;
import com.wude.http.HttpCom;
import com.wude.http.HttpUtils;
import com.wude.tools.Utils;

import org.json.JSONException;
import org.json.JSONObject;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import de.greenrobot.event.EventBus;

/**
 * Created by wude01 on 2017/10/10.
 */
@SuppressLint("HandlerLeak")
public class RegisterFragment extends CubeFragment {
    @BindView(R.id.edt_password)
    EditText edtPassword;
    @BindView(R.id.edt_phone)
    EditText edtPhone;
    @BindView(R.id.auth_code)
    EditText edtAuthCode;
    @BindView(R.id.getAuthCode)
    TextView getAuthCode;

    private CountDownTimer timer;//验证码倒计时
    private boolean isTwoGet = false;//是否是第二次获取验证码

    @Nullable
    @Override
    public View onCreateView(LayoutInflater inflater, @Nullable ViewGroup container, Bundle savedInstanceState) {
        View inflate = inflater.inflate(R.layout.register_fragment, null);
        ButterKnife.bind(this, inflate);
        initdata();
        return inflate;
    }


    @Override
    public void onResume() {
        super.onResume();
        MobclickAgent.onPageStart("RegisterFragment");
    }

    private void initdata() {
        timer = new CountDownTimer(60000, 1000) {
            @Override
            public void onTick(long l) {
                getAuthCode.setText(l / 1000 + "秒后重试");
            }

            @Override
            public void onFinish() {
                getAuthCode.setText("重新发送");
                getAuthCode.setClickable(true);
                isTwoGet = true;
            }
        };
    }

    @Override
    public void onPause() {
        super.onPause();
        if (EventBus.getDefault().isRegistered(this)) {
            EventBus.getDefault().unregister(this);
        }

        MobclickAgent.onPageEnd("RegisterFragment");
    }

    @Override
    protected View createView(LayoutInflater inflater, ViewGroup container, Bundle savedInstanceState) {
        return null;
    }


    /**
     * 重新获取验证码
     */
    private void PostMobileNumber() {
        HashMap<String, String> map = new HashMap<>();
        map.put("phone", edtPhone.getText().toString());
        map.put("type", isTwoGet ? "2" : "1");
        HttpCom.POST(handler, HttpCom.getYanzhengURL(), map, false);
    }

    /**
     * 判断手机号发送验证码
     */
    Handler handler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    try {
                        JSONObject jsonObject = new JSONObject(msg.obj.toString());
                        int status = jsonObject.getInt("status");
                        String return_code = jsonObject.getString("return_code");
                        ToastUtil.showToast(return_code);
                        if (status == 1) {
                            //验证码发送成功
                            timer.start();
                        }
                    } catch (JSONException e) {
                        e.printStackTrace();
                        Log.e("解析验证码异常", e.toString());
                    }
                    Log.e("发送验证码json", msg.obj.toString());
                    break;
                case 2:

                    break;
            }
        }
    };

    @OnClick({R.id.next, R.id.getAuthCode, R.id.xieyi})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.getAuthCode:
                if (TextUtils.isEmpty(edtPhone.getText().toString())) {
                    ToastUtil.showToast("请输入手机号码");
                    break;
                }
                if (!Utils.isMobileNO(edtPhone.getText().toString())) {
                    ToastUtil.showToast("手机号码不正确");
                    break;
                }
                PostMobileNumber();
                break;
            case R.id.next:
                int length1 = edtPassword.getText().length();
                String password = edtPassword.getText().toString();
                String authCode = edtAuthCode.getText().toString();
                if (TextUtils.isEmpty(password)) {
                    ToastUtil.showToast("请输入密码");
                    return;
                }

                if (TextUtils.isEmpty(authCode)) {
                    ToastUtil.showToast("请输入手机验证码");
                    return;
                }
                if (length1 > 12) {
                    ToastUtil.showToast("密码长度大于12位字符");
                    return;
                }
                if (length1 < 6) {
                    ToastUtil.showToast("密码长度小于6位字符");
                    return;
                }
                //注册
                regist();
                break;

            case R.id.xieyi:                            //注册协议
                Intent intent = new Intent(getContext(), WebActivity.class);
                intent.putExtra("title", "用户协议");
                intent.putExtra("url", HttpCom.getXieYi());
                startActivity(intent);
                break;
        }
    }

    public void regist() {
        HashMap<String, String> map = new HashMap<>();
        map.put("password", edtPassword.getText().toString());
        map.put("phone", edtPhone.getText().toString());
        map.put("v_code", edtAuthCode.getText().toString());
        HttpCom.POST(vhandler, HttpCom.getUserResgiterURL(), map, false);
    }

    /**
     * 注册
     */

    Handler vhandler = new Handler() {
        @Override
        public void handleMessage(Message msg) {
            super.handleMessage(msg);
            switch (msg.what) {
                case 1:
                    int i = HttpUtils.DNSRegister(msg.obj.toString());
                    switch (i) {
                        case 1:
                            //注册成功
                            ToastUtil.showToast("注册成功！");
                            getActivity().setResult(22);
                            getActivity().finish();
                            break;
                        case -1:
                            ToastUtil.showToast("用户名不合法");
                            break;
                        case -2:
                            ToastUtil.showToast("包含敏感字符");
                            break;
                        case -3:
                            ToastUtil.showToast("用户已存在");
                            break;
                        case -97:
                            ToastUtil.showToast("验证码错误");
                            break;
                    }
                    break;
                case 2:

                    break;
            }
        }
    };
}
